package com.sardine.base.design;


import com.sardine.base.design.api.ListenerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 上海京东到家元信信息技术有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/10/9
 * Time:14:11
 * robot 的监听器
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class RobotListenerContext implements InitializingBean,ApplicationContextAware {
    private static final Logger logger = LoggerFactory.getLogger(RobotListenerContext.class);
    private Map<String,List<ListenerHandler>> map=new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        /*
         取到所有实现类
        */
        Map<String, ListenerHandler> beansOfType = applicationContext.getBeansOfType(ListenerHandler.class);
        if(!CollectionUtils.isEmpty(beansOfType)){
            for (Map.Entry<String, ListenerHandler> entry : beansOfType.entrySet()) {
                ListenerHandler value = entry.getValue();
                Class<? extends ListenerHandler> aClass = value.getClass();
                if(aClass.isAnnotationPresent(EventRelay.class)){
                    EventRelay annotation = aClass.getAnnotation(EventRelay.class);
                    String eventType = annotation.eventType();
                    List<ListenerHandler> listenerHandlers = map.get(eventType);
                    if(listenerHandlers == null ){
                        listenerHandlers =new ArrayList<>();
                        map.put(eventType, listenerHandlers);
                    }
                    listenerHandlers.add(value);
                }
            }
        }
        logger.info("robot ContextConfig init success...{}",map.size());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ContextConfig config=new ContextConfig(map);
        RobotContext context=RobotContext.getInstance();
        context.setContextConfig(config);
        for (Map.Entry<String, List<ListenerHandler>> stringListEntry : map.entrySet()) {

            logger.info("robot afterPropertiesSet init success key:{},size：{}", stringListEntry.getKey(),stringListEntry.getValue().size());
        }
    }
}
